<template>
  <div class="app-container">
    <!--    <el-row :gutter="10" class="mb8">-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button type="primary" plain size="mini" @click="disconnectBtn">断开连接</el-button>-->
    <!--      </el-col>-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button type="success" plain size="mini" @click="disconnectBtn">停止输出-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button type="success" plain size="mini" @click="loadChat">发送请求-->
    <!--        </el-button>-->
    <!--      </el-col>-->
    <!--    </el-row>-->

    <div class="container">
      <table border="1">
        <tbody id="chat">
        <tr>
          <td>
            <div>
              默认保持连接5分钟，默认上下文保持10个，5分钟无请求上下文会话销毁。
            </div>
          </td>
        </tr>
        </tbody>
      </table>
      <div class="input-card">
        <div class="input-card-item">
          <el-input v-model="inputMessage" id="message" type="textarea" :autosize="{ minRows: 2, maxRows: 6 }"
                    placeholder="输入你的问题，回车结束......" @keydown.enter.native="sendMessage($event)">
            <template slot="append" @click="sendMessage">
              <el-button type="primary">发送</el-button>
            </template>
          </el-input>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import marked from './markdown.min'
import {chatGptCharging} from "@/api/chat/chatGtp"

export default {
  name: "index",
  data() {
    return {
      socket: "",
      inputMessage: "",//输入框内容
      userId: "",
      uuid_str: "",
      chat: ""
    }
  },
  mounted() {
    this.userId = this.$store.getters.userId
    this.loadChat()
  },
  methods: {
    // 发送消息
    sendMessage(event) {
      console.log('event', event)
      if (!event.ctrlKey) { // 如果没有按下组合键ctrl，则会阻止默认事件
        event.preventDefault();
        this.uuid_str = this.uuid();
        chatGptCharging().then(res => {
          this.pushMessage()
        })
      } else {
        // 如果同时按下ctrl+回车键，则会换行
        this.inputMessage += '\n';
      }
    },
    pushMessage() {
      this.socket.send(this.inputMessage);
      //新增问题框
      this.chat.innerHTML += '<tr><div style="color: #fff;padding: 10px">' +
        '<span style="border-radius: 10px;background-color: #00afff;padding: 10px;width: fit-content；">' + this.inputMessage + '</span>' +
        '</div></tr>';
      this.inputMessage = null
      //新增答案框
      this.chat.innerHTML += '<tr><div style="border-radius:10px;border: 1px solid #626161;padding: 0 10px;margin-left: 10px" id="' + this.uuid_str + '" class="markdown-body"></div></tr>';
    },
    // 断开连接
    disconnectBtn() {
      if (this.socket) {
        this.socket.close();
      }
    },
    // 初始化websocket
    loadChat() {
      var that = this;
      this.chat = document.getElementById("chat");
      let uuid_str = '';
      let text = '';
      let uid = window.localStorage.getItem("uid");
      if (uid == null || uid == '' || uid == 'null') {
        uid = that.uuid();
      }
      // 设置本地存储
      window.localStorage.setItem("uid", uid);
      if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        //实现化WebSocket对象
        //指定要连接的服务器地址与端口建立连接
        //注意ws、wss使用不同的端口。我使用自签名的证书测试，
        //无法使用wss，浏览器打开WebSocket时报错
        //ws对应http、wss对应https。
        this.socket = new WebSocket("wss://pbb2c.com/wst/websocket/" + uid);
        //连接打开事件
        this.socket.onopen = function () {
          console.log("Socket 已打开");
        };
        //收到消息事件
        this.socket.onmessage = function (msg) {
          // console.log('收到消息', msg)
          if (msg.data == "[DONE]") {
            text = '';
            return;
          }
          let json_data = JSON.parse(msg.data)
          if (json_data.content == null || json_data.content == 'null') {
            text = '';
            return;
          }
          text = text + json_data.content;
          that.setText(text, uuid_str)
        };
        //连接关闭事件
        this.socket.onclose = function () {
          console.log("Socket已关闭");
        };
        //发生了错误事件
        this.socket.onerror = function () {
          alert("服务异常请重试并联系开发者！")
        }
        //窗口关闭时，关闭连接
        window.unload = function () {
          this.socket.close();
        };
      }
    },

    setText(text, uuid_str) {
      let content = document.getElementById(this.uuid_str)
      content.innerHTML = marked(text);
    },
    uuid() {
      var s = [];
      var hexDigits = "0123456789abcdef";
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = "-";

      var uuid = s.join("");
      return uuid;
    }
  }
}
</script>

<style scoped>

/**改变input里的字体颜色*/
/deep/ input::-webkit-input-placeholder {
  color: #00bcff;
  font-size: 12px;
}

/**改变input框背景颜色*/
/deep/ .el-input__inner {
  background-color: transparent !important;
}

.markdown-body {
  box-sizing: border-box;
  min-width: 200px;
  max-width: 980px;
  margin: 0 auto;
  padding: 45px;
  font-size: 100px;
  background-color: #5af107;
}

@media (max-width: 767px) {
  .markdown-body {
    padding: 15px;
    font-size: 100px;
  }
}

input {
  height: 50px;
  width: 500px;
  font-size: 20px;
  /*background: url(10) no-repeat;*/
  /*background-color: #1e1e1e;*/
  color: #d0838e;
}

.container {
  /*margin: auto;*/
  min-width: 600px;
  border: 1px solid #0986e3;
  display: flex;
  flex-direction: column;
  border-radius: 10px;
  padding: 10px;
  margin-bottom: 50px;
}

.input-card {
  position: fixed;
  display: inline-block;
  bottom: 0;
  right: 20%;
  left: 20%;
  margin: auto;
}

.input-card-item {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.float-card {
  position: fixed;
  display: inline-block;
  right: 120px;
  top: 100px;
}

.float-card-item {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #ccccd6;
  margin-bottom: 16px;
}

.float-card-item:last-child {
  margin-bottom: 0px;
  background-color: #d0838e;
}

.float-card-item a {
  text-decoration: none;
  color: #594649;
  font-size: 13px;
}
</style>
